<?php

/**
 * 威廉国际SDK
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopWlgjApi;
use App\Service\BaseService;
use App\Service\Code\Normal;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

class ShopWlgjApiClient extends BaseService
{
    private $api_url;
    private $app_secrete;
    private $app_key;
    
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct()
    {
        $this->api_url      = config("api.shopwlgj.api_url");
        $this->app_secrete  = config("api.shopwlgj.app_secrete");
        $this->app_key      = config("api.shopwlgj.app_key");
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        $orderInfo  = $param['supplierOrder'];
        $goodsList  = $param['orderGoods'];
        //处理收获地址问题
        $receiveAddress = implode("", [
            $orderInfo['province'],
            " ",
            $orderInfo['city'],
            " ",
            $orderInfo['district'],
            " ",
            $orderInfo['receive_address'],
        ]);
        
        //商品下单组
        $orderGoodsList = [];
        $productAmt = 0 ;
        foreach ($goodsList as $item ) 
        {
            $price          = $item['price'];
            $quantity       = $item['quantity'];
            $orderGoodsList[] = [
                'protitle'  =>  $item['goods_name'],
                'prono'     =>  $item['supplier_skucode'],
                'prosku'    =>  $item['supplier_skucode'],
                'proprice'  =>  (float)$price,
                'procount'  =>  $quantity
            ];
            $productAmt = bcadd($productAmt, bcmul($quantity, $price,2),2);
        }
        
        //运费
        $delivery   = isset($orderInfo['deliver_money']) ? $orderInfo['deliver_money'] : 0.00;
        //下单总金额(商品总金额 + 总运费)
        $totalMoney = bcadd($productAmt, $delivery,2);
        
        //组装推送上游数据
        $requestData = [
            "orderNo"       => $orderInfo['supplier_dsn'],//S2B 子单号
            "UserName"      => $orderInfo['receive_name'],
            "uName"         => $orderInfo['receive_name'],//收件人姓名[必填]
            "province"      => $orderInfo['province'],//省份[必填]
            "city"          => $orderInfo['city'],//城市[必填]
            "district"      => $orderInfo['district'],//区域[必填]
            "address"       => $receiveAddress,//地址[必填]
            "postcode"      => "000000",//邮编[必填]
            "mobiTel"       => $orderInfo['buyer_phone'],//手机号码[可填][注：手机号码和电话号码至少填一项]
            "phone"         => $orderInfo['recveive_phone'],//电话号码[可填][注：手机号码和电话号码至少填一项]
            "cRemark"       => $orderInfo['order_remark'],//买家留言[可填]
            "oRemark"       => "",//卖家备注[可填]
            "oSumPrice"     => (float)$totalMoney,//实付订单总金额[必填]
            "expFee"        => (float)$delivery,//实付订单运费[可填][默认为0]
            "expCod"        => "0",//是否货到付款[必填][1：货到付款]
            "codFee"        => "0",//货到付款手续费[可填][默认为0]
            "expCodFee"     => "0",//货到付款代收运费[可填][默认为0]
            "OrderPro"      => str_replace('&', '',  json_encode($orderGoodsList,JSON_UNESCAPED_UNICODE))
        ];
        
        $requestParam = [
            'method' => 'createOrder',
            'data' => $requestData
        ];
        
        $res = $this->execute($requestParam);
        if( $res['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"推送订单成功",[
                'thirdpart_order_sn' => $res['data']['Result']
            ]);
        }
        return $res;
    }
    
    /**
     * 查询商品
     * @param array $param
     */
    public function queryGoods( $param = [] )
    {
        $requestData = [
            'proSale' => 0,
        ];
        $requestParam = [
            'method' => 'queryGoodsLists',
            'data' => $requestData
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 订单售后
     * @param array $params
     * @return mixed
     */
    public function orderAfter( $param = [] )
    {
        $supplierOrder = $param['supplierOrder'];
        $order         = $param['order'];
        $requestParam = [
            'method' => 'orderAfter',
            'data' => [
                'orderId'       => $supplierOrder['thirdpart_order_sn'],
                'cancelReason'  => $order['exceptReason'] ?? '不想要了'
            ],
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 取消订单
     * @param array $params
     * @return mixed
     */
    public function cancelOrder( $param = [] ) 
    {
        $supplierOrder = $param['supplierOrder'];
        $order         = $param['order'];
        $requestParam = [
            'method' => 'cancelOrder',
            'data' => [
                'orderId'       => $supplierOrder['thirdpart_order_sn'],
                'cancelReason'  => $order['exceptReason'] ?? '不想要了'
            ],
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 获取订单的发货状态
     */
    public function orderExpress( $params = [] ) 
    {
        //请求参数
        $requestParam = [
            'method'    => 'orderExpress',
            'data'      => $params
        ];

        return $this->execute($requestParam);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $config = config("api.shopwlgj");
        $method = $config['route'][$param['method']];
        
        $commonParam = [
            'user'      => $this->app_key,
            'method'    => $method,
            'token'     => $this->getSign(['data' => $param['data'],'method' => $method]),
            'format'    => 'json',
            'appKey'    => $this->app_key
        ];
        
        $data       = array_merge($param['data'],$commonParam);
        $data       = urldecode(http_build_query($data));
        $start_time = microtime(true);
        
        $parameter = [
            [
                'tag'       => 'shopwlgj_'.$param['method'],
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $this->api_url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'form-data',
                'header'    => [],
            ],
        ];
        
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $result  = @json_decode($resTask['response']['result'],true);
        $message = $result['Message'] ?? '请求失败';
        if( $result['Code'] == '101' ) {
            return Normal::returnCode(Normal::SUC,$message,$result);
        } else {
            return Normal::returnCode(Normal::FAIL,$message);
        }
    }

    private function mbstringtoarray($str,$charset) {//分割字符
        $strlen=mb_strlen($str);
        while($strlen){
            $array[]=mb_substr($str,0,1,$charset);
            $str=mb_substr($str,1,$strlen,$charset);
            $strlen=mb_strlen($str);
        }
        return $array;
    }
    
    /**
     * 获取sign参数
     */
    private function getSign( $param = [] ) {

        $apiMethod = $param['method'];
        $postData = '';
        foreach ($param['data'] as $k => $v){
            $postData.= $k.$v;
        }
        $inputStr = strtolower(str_replace(" ","",$this->app_secrete.$apiMethod."appKey".$this->app_key.$postData));//转小写
        //分割字符串组装成数组
        $sort   =  $this->mbstringtoarray($inputStr,'utf-8');
        //对数组进行排序
        sort($sort,SORT_STRING);
        $str="";
        //从新组装成字符串
        foreach($sort as $val){
            $str.=$val;
        }
        $paramStr = $str;
        //进行MD5加密生成TOKEN
        $sToken = md5($paramStr);
        return $sToken;
    }
}